﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BingWallpaper
{
    public partial class Form1 : Form
    {
        private string staticUrl = "http://www.bing.com/HPImageArchive.aspx?format=js&idx={0}&n=1&mkt=en-US";
        private static string path = string.Empty;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dia = new FolderBrowserDialog();
            dia.ShowDialog();
            path = dia.SelectedPath;
            this.lab_path.Text = dia.SelectedPath;
            //Directory.CreateDirectory(formPath + "set.txt");
            var formPath = System.AppDomain.CurrentDomain.BaseDirectory;
            StreamWriter sw = new StreamWriter(formPath + "set.txt", false);
            sw.WriteLine(dia.SelectedPath);
            sw.Dispose();
            if (!string.IsNullOrWhiteSpace(this.lab_path.Text))
            {
                this.btn_show.Enabled = true;
                this.btn_setWallPaper.Enabled = true;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var formPath = System.AppDomain.CurrentDomain.BaseDirectory;
            if (File.Exists(formPath + "set.txt"))
            {
                StreamReader sr = new StreamReader(formPath + "set.txt", Encoding.UTF8);
                var line = sr.ReadLine();
                this.lab_path.Text = line;
                path = line;
                sr.Dispose();
            }
            if (string.IsNullOrWhiteSpace(this.lab_path.Text))
            {
                this.btn_show.Enabled = false;
                this.btn_setWallPaper.Enabled = false;
            }
        }


        [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
        public static extern int SystemParametersInfo(
         int uAction,
         int uParam,
         string lpvParam,
         int fuWinIni
         );

        private async void btn_setWallPaper_Click(object sender, EventArgs e)
        {
            var url = string.Format(staticUrl, 0);
            var result = await GetImageJson(url, string.Empty);
            if (string.IsNullOrEmpty(path))
            {
                MessageBox.Show("请先设置存储路径");
            }
            else
            {
                var savePath = await SaveImageFromWeb("http://cn.bing.com/" + result["url"], path, result["fullstartdate"]);
                Image image = Image.FromFile(savePath);
                image.Save(".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                SystemParametersInfo(20, 0, savePath, 0x2);
                image.Dispose();
                MessageBox.Show("成功！");
            }
        }

        private async Task<Dictionary<string, string>> GetImageJson(string Url, string postDataStr)
        {
            WebRequest wrq = WebRequest.Create("http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN");
            WebResponse wrp = wrq.GetResponse();
            Stream stream = wrp.GetResponseStream();
            StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
            string String_JSON = await sr.ReadToEndAsync();
            JObject Obj_JSON = JObject.Parse(String_JSON);
            string String_Images = Obj_JSON["images"][0].ToString();
            String_Images = String_Images.Remove(String_Images.Length - 16, 14);//删除末端无法识别的hs
            Dictionary<string, string> Dic_Images = JsonConvert.DeserializeObject<Dictionary<string, string>>(String_Images);
            return Dic_Images;// @"http://cn.bing.com/" + Dic_Images["url"];
        }

        public async static Task<string> SaveImageFromWeb(string imgUrl, string path, string fileName)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                MessageBox.Show("未指定保存文件的路径");
                return string.Empty;
            }
            string imgName = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("/") + 1);
            string defaultType = ".jpg";
            string[] imgTypes = new string[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
            string imgType = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("."));
            string imgPath = "";
            foreach (string it in imgTypes)
            {
                if (imgType.ToLower().Equals(it))
                    break;
                if (it.Equals(".bmp"))
                    imgType = defaultType;
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgUrl);
            request.UserAgent = "Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; Natas.Robot)";
            request.Timeout = 3000;

            WebResponse response = await request.GetResponseAsync();
            Stream stream = response.GetResponseStream();

            if (response.ContentType.ToLower().StartsWith("image/"))
            {
                byte[] arrayByte = new byte[1024];
                int imgLong = (int)response.ContentLength;
                int l = 0;

                if (fileName == "")
                    fileName = imgName;
                FileStream fso = new FileStream(path + "\\" + fileName + imgType, FileMode.Create);
                while (l < imgLong)
                {
                    int i = await stream.ReadAsync(arrayByte, 0, 1024);
                    await fso.WriteAsync(arrayByte, 0, i);
                    l += i;
                }

                fso.Dispose();
                stream.Dispose();
                response.Dispose();
                imgPath = fileName + imgType;
                return path + "\\" + fileName + imgType;
            }
            else
            {
                return "";
            }
        }

        private async void btn_show_Click(object sender, EventArgs e)
        {
            var url = string.Format(staticUrl, 0);
            var result = await GetImageJson(url, string.Empty);
            var savePath = await SaveImageFromWeb("http://cn.bing.com/" + result["url"], path, result["fullstartdate"]);
            var fs = new System.IO.FileStream(savePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            this.pic_box.Image = Image.FromStream(fs);
            fs.Close();

            //System.Diagnostics.Process.Start(savePath.Trim());
        }

        private void btn_reload_Click(object sender, EventArgs e)
        {
            btn_show_Click(null, null);
            DialogResult dr = MessageBox.Show("刷新成功，是否设置成壁纸?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (dr == DialogResult.OK)
            {
                btn_setWallPaper_Click(null, null);
            }
        }
    }

    public class BingImg
    {
        public string url { get; set; }
    }

}

